﻿using Kiwi.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace Kiwi.ViewModel
{
    public class CbCommentViewModel : ViewModelBase
    {
        protected override string RssUrl
        {
            get
            {
                return base.RssUrl;
            }
        }

        protected override void Request()
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += ReadRSSCompleted;
            client.DownloadStringAsync(new Uri(RssUrl, UriKind.RelativeOrAbsolute));
        }

        void ReadRSSCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string meta_content = HttpUtility.HtmlDecode(e.Result);

            XDocument xdocument = XDocument.Load(new StringReader(meta_content));

            var items = (from element in xdocument.Descendants("item")
                         select GetCommentModel(element));

            CommentCollection = new ObservableCollection<CommentInfo>(items);
            RaisePropertyChanged(() => CommentCollection);
        }

        private CommentInfo GetCommentModel(XElement element)
        {
            string content = element.Element("description").Value;
            int index = content.LastIndexOf("<br />");

            CommentInfo item = new CommentInfo();

            item.Description = Regex.Replace(content.Substring(0, index), "<(.[^><]*)>", "\r\n");
            item.Author = content.Substring(index).Replace("<br />", "");

            item.Link = element.Element("link").Value;
            item.Time = DateTime.Parse(element.Element("pubDate").Value);

            return item;
        }
    }
}
